import axios, { AxiosError } from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { useGlobalStore } from '@/stores'
import type { Result } from '@/api/interface'
import { ElMessage } from 'element-plus'
import router from '@/router'

const config = {
  baseURL: '/api',
  timeout: 5000,
}

const store = useGlobalStore()

class RequestHttp {
  service: AxiosInstance
  public constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config)

    // 请求拦截
    this.service.interceptors.request.use(
      async (config: AxiosRequestConfig | any) => {
        config.headers.Authorization = `Bearer ${store.access_token}`
        return config
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      },
    )

    // 响应拦截
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response
        // code状态码处理
        if (data.code === 200) {
          return data
        } else {
          ElMessage.error(data.data)
          return Promise.reject(data.message)
        }
      },
      async (error: any) => {
        const { data } = error.response
        ElMessage.error(data.message)
        if (data.code === 401) {
          router.push('/login')
        } else {
          // 常规异常时触发
          return Promise.reject(data.message)
        }
      },
    )
  }

  // * 常用请求方法封装
  get<T>(url: string, params?: object, _object = {}): Promise<Result<T>> {
    return this.service.get(url, { params, ..._object })
  }
  post<T>(url: string, params?: object, _object = {}): Promise<Result<T>> {
    return this.service.post(url, params, _object)
  }
  put<T>(url: string, params?: object, _object = {}): Promise<Result<T>> {
    return this.service.put(url, params, _object)
  }
  delete<T>(url: string, params?: object, _object = {}): Promise<Result<T>> {
    return this.service.delete(url, { params, ..._object })
  }
}
export default new RequestHttp(config)
